package api

import (
	"gitee.com/zhaokangming/tiny-ticktok/pkg/app"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/constants"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/errcode"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/util/auth"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/util/convert"
	"gitee.com/zhaokangming/tiny-ticktok/service"

	"github.com/gin-gonic/gin"
)

// FavoriteAction create or delete favorite of a video
func FavoriteAction(c *gin.Context) {
	claims, ok := c.Value("claims").(*auth.Claims)
	if !ok {
		app.WriteResponse(c, errcode.ErrAuthCheckToken, nil)
		return
	}

	vid, ok := c.GetQuery("video_id")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	action, ok := c.GetQuery("action_type")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	if action == constants.Action {
		err := service.Favorite(c, claims.ID, convert.StrTo(vid).MustInt64())
		app.WriteResponse(c, err, nil)
		return
	}

	if action == constants.ActionCancel {
		err := service.CancelFavorite(c, claims.ID, convert.StrTo(vid).MustInt64())
		app.WriteResponse(c, err, nil)
		return
	}

	app.WriteResponse(c, errcode.ErrParamTypeError, nil)
}

// FavoriteList get favorite list
func FavoriteList(c *gin.Context) {
	claims, ok := c.Value("claims").(*auth.Claims)
	if !ok {
		app.WriteResponse(c, errcode.ErrAuthCheckToken, nil)
		return
	}

	userID, ok := c.GetQuery("user_id")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	var targetID int64
	if userID == "0" {
		targetID = claims.ID
	} else {
		targetID = convert.StrTo(userID).MustInt64()
	}

	res, err := service.GetFavoriteList(c, claims.ID, targetID)
	if err != nil {
		app.WriteResponse(c, err, nil)
		return
	}

	app.WriteResponse(c, nil, res)
}
